package com.yzt.zhuju.gift;

import android.app.Dialog;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.yzt.zhuju.R;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.dialog.BaseDialog;
import com.yzt.zhuju.network.entity.gift.Gift;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.plugin_widget.RoundImageView;

import java.util.HashMap;
import java.util.Map;

/**
 * author : bob
 * date   : 2022/12/5
 * desc   :
 */
public class GiftAnimDialogFragment extends BaseDialog {

    private FrameLayout flowersLayout;
    private View firtGiftView;
    private ImageView firstGiftImg;
    private TextView firstGiftText;
    private TextView tvFirstGiftDetail;
    private TextView firstGiftNumTv;
    private RoundImageView rivhoto1;

    private View secGiftView;
    private ImageView secGiftgif;
    private ImageView secGiftImg;
    private TextView secGiftText;
    private TextView secGiftNumTv;

    private Gift mGift;
    private String mUserName;
    // 存id, num
    private final Map<Integer, Integer> mGiftMap = new HashMap<>();

    //字体
    private Typeface mFont;
    private GiftCountDownTimer mFirstTimer;
    private GiftCountDownTimer mSecTimer;
    private Animation mGiftAnim = null;

    private boolean isNormalAnimStop = false;
    private final boolean isSpecialAnimStop = true;

    @Override
    public int getGravity() {
        return Gravity.LEFT;
    }

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_ubi_send_anim_gift;
    }

    @Override
    public void bindView(View view) {
        Bundle data = getArguments();
        mGift = (Gift) data.getSerializable("gift");
        mUserName = data.getString("username");
        initView(view);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.dialog);
        AssetManager mgr = getActivity().getAssets();//得到AssetManager
        mFont = Typeface.createFromAsset(mgr, "fonts/num1.ttf");//根据路径得到Typeface
        mGiftAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_click_likes);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null && getDialog().getWindow() != null) {
            // 设置宽度为屏宽, 靠近屏幕底部。
            Window win = getDialog().getWindow();
            // 一定要设置Background，如果不设置，window属性设置无效
            win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            WindowManager.LayoutParams params = win.getAttributes();
            params.gravity = Gravity.LEFT;
            // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            win.setAttributes(params);
        }
    }

    public void updateGift(Gift gift) {
        Integer giftNum = mGiftMap.get(gift.getId());
        if (giftNum == null) { //礼物不存在,弹出来
            isStart = false;
            if (mGiftMap.size() == 0) {
                createFirstCountDownTimer();
                startFadeAnim(flowersLayout, firtGiftView, firstGiftImg, firstGiftText, tvFirstGiftDetail, rivhoto1,
                        firstGiftNumTv, gift.getId(), gift.getIcon(), gift.getUnit(), gift.getName(), gift.getNum());
            } else if (mGiftMap.size() == 1) {
                if (firtGiftView.getVisibility() == View.VISIBLE) {
                    createSecCountDownTimer();
                    startFadeAnim(flowersLayout, secGiftView, secGiftImg, secGiftText, tvFirstGiftDetail, rivhoto1,
                            secGiftNumTv, gift.getId(), gift.getIcon(), gift.getUnit(), gift.getName(), gift.getNum());
                } else {
                    createFirstCountDownTimer();
                    startFadeAnim(flowersLayout, firtGiftView, firstGiftImg, firstGiftText, tvFirstGiftDetail, rivhoto1,
                            firstGiftNumTv, gift.getId(), gift.getIcon(), gift.getUnit(), gift.getName(), gift.getNum());
                }
            }
            mGiftMap.put(gift.getId(), 1);
        } else {  //礼物存在 只改变显示的数据
            if (!isStart) {
                return;
            }
            Integer firstTag = (Integer) firtGiftView.getTag();
            Integer secTag = (Integer) secGiftView.getTag();

            int curGiftNum = giftNum + 1;

            if (gift.getWorthUnit() == 2) {
                if (curGiftNum * gift.getWorth() > RXingUtils.getRemainDiamond()) {
                    ToastUtil.showMessage(R.string.money_not_enough);
                    return;
                }
            }

            if (firstTag == gift.getId()) {
                startScaleAnim(firstGiftNumTv, curGiftNum);
                createFirstCountDownTimer();
            } else if (secTag == gift.getId()) {
                startScaleAnim(secGiftNumTv, curGiftNum);
                createSecCountDownTimer();
            }
            mGiftMap.put(gift.getId(), curGiftNum);
        }
    }

    private void createFirstCountDownTimer() {
        if (mFirstTimer != null) {
            mFirstTimer.cancel();
            mFirstTimer = null;
        }
        mFirstTimer = new GiftCountDownTimer(2000, 500, FIRST_FLAG);
        mFirstTimer.start();
    }

    private void createSecCountDownTimer() {
        if (mSecTimer != null) {
            mSecTimer.cancel();
            mSecTimer = null;
        }
        mSecTimer = new GiftCountDownTimer(2000, 500, SEC_FLAG);
        mSecTimer.start();
    }

    private void initView(View view) {
        firtGiftView = view.findViewById(R.id.gift_panel_1);
        firstGiftImg = view.findViewById(R.id.dialog_gift_image_1);
        firstGiftText = view.findViewById(R.id.tv_you_give_1);
        tvFirstGiftDetail = view.findViewById(R.id.tv_gift_1);
        rivhoto1 = view.findViewById(R.id.riv_photo_1);
        firstGiftNumTv = view.findViewById(R.id.dialog_gift_num_1);
        firstGiftNumTv.setTypeface(mFont);//设置字体

        secGiftView = view.findViewById(R.id.gift_panel_2);
        secGiftgif = view.findViewById(R.id.dialog_gift_gif_2);
        secGiftImg = view.findViewById(R.id.dialog_gift_image_2);
        secGiftText = view.findViewById(R.id.dialog_gift_info_2);
        secGiftNumTv = view.findViewById(R.id.dialog_gift_num_2);
        secGiftNumTv.setTypeface(mFont);//设置字体

        flowersLayout = view.findViewById(R.id.rlt_animation_layout);

        Dialog dialog = getDialog();
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams wmlp = window.getAttributes();
            wmlp.gravity = Gravity.LEFT;
            window.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        }
        dialog.setCanceledOnTouchOutside(false);
        if (mFirstTimer == null) {
            mFirstTimer = new GiftCountDownTimer(2000, 500, FIRST_FLAG);
        }
        mFirstTimer.start();

        mGiftMap.put(mGift.getId(), mGift.getNum());

        startFadeAnim(flowersLayout, firtGiftView, firstGiftImg, firstGiftText, tvFirstGiftDetail, rivhoto1,
                firstGiftNumTv, mGift.getId(), mGift.getIcon(), mGift.getUnit(), mGift.getName(), mGift.getNum());
    }

    private void startFadeAnim(FrameLayout flowersLayout, View view, final ImageView giftImg,
                               final TextView giftText, final TextView tvFirstGiftDetail, final RoundImageView rivhoto1, final TextView giftNumText, final int giftId,
                               final String giftPath, final String giftUnit, final String giftName, final int giftNum) {
        if (view == null) {
            return;
        }

        TranslateAnimation bottomOutAnim = new TranslateAnimation(-DisplayUtils.getDisplayPxWidth(), 0, 0, 0);
        bottomOutAnim.setDuration(500);
        bottomOutAnim.setInterpolator(new DecelerateInterpolator());

        bottomOutAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                ImageLoadUtil.loadIv(giftImg.getContext(), giftPath, giftImg);
                ImageLoadUtil.loadCircle(rivhoto1.getContext(), RXingUtils.getLoginAccount().getUserInfo().getAvatar(), rivhoto1, R.mipmap.icon_placeholder);
                giftText.setText(RXingUtils.getLoginAccount().getUserInfo().getUserName() + " to " + mUserName);
                tvFirstGiftDetail.setText(giftNum + giftUnit + giftName);
                startScaleAnim(giftNumText, giftNum); //启动的晚
                isStart = true;
            }
        });

        view.setTag(giftId);
        view.setVisibility(View.VISIBLE);
        view.startAnimation(bottomOutAnim);
    }

    private boolean isStart = false;

    private void startScaleAnim(TextView giftNumText, int giftNum) {
        giftNumText.setVisibility(View.VISIBLE);
        giftNumText.setText("X " + giftNum);
        giftNumText.startAnimation(mGiftAnim);
    }

    private final int FIRST_FLAG = 1;
    private final int SEC_FLAG = 2;

    private class GiftCountDownTimer extends CountDownTimer {

        private final int flag;

        public GiftCountDownTimer(long millisInFuture, long countDownInterval, int flag) {
            super(millisInFuture, countDownInterval);
            this.flag = flag;
        }

        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            try {
                if (flag == FIRST_FLAG) { //第一个CountDownTimer
                    Integer firstGiftId = (Integer) firtGiftView.getTag();
                    Integer firstGiftNum = mGiftMap.get(firstGiftId);
                    if (firstGiftId != null && firstGiftNum != null) {
                        if (mSendGiftListener != null) {
//                            if (mGift.getType() == 1) {
//                                mSendGiftListener.sendIntimateGift(mGift.getBigType(), firstGiftId, firstGiftNum);
//                            } else {
                            mSendGiftListener.sendGift(mGift.isSendSelf(), mGift.getTabId(), mGift.getBigType(), firstGiftId, firstGiftNum);
//                            }
                        }
                    }
                    mGiftMap.remove(firstGiftId);
                    firtGiftView.setVisibility(View.GONE);
                } else if (flag == SEC_FLAG) { //第二个CountDownTimer
                    Integer secGiftId = (Integer) secGiftView.getTag();
                    Integer secGiftNum = mGiftMap.get(secGiftId);
                    if (secGiftId != null && secGiftNum != null) {
                        if (mSendGiftListener != null) {
//                            if (mGift.getType() == 1) {
//                                mSendGiftListener.sendIntimateGift(mGift.getBigType(), secGiftId, secGiftNum);
//                            } else {
                            mSendGiftListener.sendGift(mGift.isSendSelf(), mGift.getTabId(), mGift.getBigType(), secGiftId, secGiftNum);
//                            }
                        }
                    }
                    mGiftMap.remove(secGiftId);
                    secGiftView.setVisibility(View.GONE);
                }
                if (mGiftMap.size() == 0) {
                    isNormalAnimStop = true;
                    dismissDialog();
                }
            } catch (Exception ignored) {

            }
        }
    }

    private void dismissDialog() {
        try {
            if (isNormalAnimStop && isSpecialAnimStop) {
                setCancelable(true); //设置后，可重新生成GiftAnimDialogFragment
                dismiss();
            }
        } catch (Exception ignored) {

        }
    }

    private SendGiftListener mSendGiftListener;

    public void setSendGiftListener(SendGiftListener sendGiftListener) {
        this.mSendGiftListener = sendGiftListener;
    }

    public interface SendGiftListener {

        void sendGift(boolean sendSelf, int tabId, int bigType, int giftId, int giftNum); //发送
    }
}

